package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	cachego "text/cache"
	"text/model"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段禁止为空",
		})
		return
	}
	data := model.Article{
		//Model:   gorm.Model{},
		Title:   title,
		Content: content,
	}
	err := model.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布错误",
		})
		return
	}
	var article model.Article
	model.DB.Where("id = ?", data.ID).Find(&article)
	redis_key := "article_" + strconv.Itoa(int(data.ID))
	jsonData, _ := json.Marshal(&article)
	cachego.Rdb.Set(cachego.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
}
func Del(c *gin.Context) {
	id := c.Query("id")
	var article model.Article
	err := model.DB.Where("id = ?", id).Debug().Delete(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除错误",
		})
	}
	redis_key := "article_" + id
	cachego.Rdb.Del(cachego.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}
func List(c *gin.Context) {
	var articles []model.Article

	redis_key := "list"
	cacheData, _ := cachego.Rdb.Get(cachego.Ctx, redis_key).Result()
	if cacheData == "" {
		err := model.DB.Debug().Find(&articles).Error
		jsonData, _ := json.Marshal(&articles)
		cachego.Rdb.Set(cachego.Ctx, redis_key, jsonData, time.Hour*2)
		if err != nil {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "展示失败",
			})
		}
	} else {
		json.Unmarshal([]byte(cacheData), &articles)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": articles,
	})

}
